package cn.dulian.spring5.dao;

import cn.dulian.spring5.bean.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.List;

/**
 * @author dulian
 * @create 2022-04-15 22:36
 */
@Repository
public class BookDaoImpl implements BookDao{
    //注入JdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void add(Book book) {
        String sql="insert into bookinfo values(?,?,?)";
        //调用方法实现
        Object[] args = {book.getUserId(),book.getUsername(),book.getUstatue()};
        int update = jdbcTemplate.update(sql, args);
        System.out.println(update);
    }

    @Override
    public void updateBook(Book book) {
        String sql ="update bookinfo set username=?,ustatus=? where userId =?";
        Object[] args = {book.getUsername(),book.getUstatue(),book.getUserId()};
        int update = jdbcTemplate.update(sql, args);
        System.out.println(update);
    }

    @Override
    public void delete(int id) {
        String sql = "delete from bookinfo where userId =?";
        int update = jdbcTemplate.update(sql, id);
        System.out.println(update);
    }

    @Override
    public void selectCount() {
        String sql ="select count(1) from bookinfo";
        Integer integer = jdbcTemplate.queryForObject(sql, Integer.class);
        System.out.println(integer);
    }

    @Override
    public Book findBookInfo(int id) {
        String sql ="select * from bookinfo where userId = ?";
        Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Book.class),id);
        return book;
    }

    @Override
    public List<Book> findAll() {
        String sql ="select * from bookinfo";
        List<Book> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Book.class));
        return query;
    }

    @Override
    public void batchInsert(List<Object[]> batchArgs) {
        String sql="insert into bookinfo values(?,?,?)";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }

    @Override
    public void batchdelect(List<Object[]> batchArgs) {
        String sql="update bookinfo set username=?,ustatus=? where userId=?";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }

    @Override
    public void batchupdate(List<Object[]> batchArgs) {
        String sql="delete from bookinfo where userId =?";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }
}
